package com.itheima.filter;

import com.itheima.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        //获取到请求路径
        String requestURI = request.getRequestURI();
        //判断是否是登录请求 请求路径包含/login
        if(requestURI.contains("/login")){
            log.info("登录请求,放行");
            filterChain.doFilter(request,response);
            return;
        }

        //获取token
        String token = request.getHeader("token");

        //判断token是否存在 如果不存在说明用户没有登录直接返回错误信息
        if(token==null || token.isEmpty()){
            log.info("令牌为空");
            response.setStatus(401);
            return;
        }

        //令牌存在校验令牌
        try {
            JwtUtils.parseToken(token);
        } catch (Exception e) {
            log.info("令牌不合法");
        }

        //校验通过放行
        filterChain.doFilter(request,response);
        log.info("令牌校验通过");
    }
}
